package com.tanran.taolijin.service.impl;

import com.tanran.taolijin.model.TaobaoUser;
import com.tanran.taolijin.repository.TaobaoUserRepository;
import com.tanran.taolijin.service.TaobaoUserService;
import com.tanran.taolijin.util.Result;
import com.tanran.taolijin.util.TextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * Created by Enzo Cotter on 2019/11/4.
 */
@Service
public class TaobaoUserServiceImpl implements TaobaoUserService {
    @Autowired
    private TaobaoUserRepository taobaoUserRepository;

    @Override
    public Result login(TaobaoUser taobaoUser, HttpSession session) {
        TaobaoUser dbTaobaoUser = taobaoUserRepository.findByUserNameAndPassWord(taobaoUser.getUserName(), taobaoUser.getPassWord());
        if(!Objects.isNull(dbTaobaoUser)){
            session.setAttribute("user",dbTaobaoUser);
            return Result.ok("登陆成功");
        }
        return  Result.error("登陆失败");
    }

    @Override
    public Result register(TaobaoUser taobaoUser) {
        TaobaoUser dbTaobaoUser = taobaoUserRepository.findByUserName(taobaoUser.getUserName());
        if(!Objects.isNull(dbTaobaoUser)){
            return Result.error("用户名已被注册");
        }
        taobaoUser.setIsAdmin(0);
        taobaoUser.setTaobaoCount(0);
        taobaoUser.setId(TextUtil.getUUID().substring(16,30));
        if(!StringUtils.isEmpty(taobaoUserRepository.save(taobaoUser).getId())){
            return  Result.ok("注册成功");
        }
        return  Result.error("注册失败");
    }
}
